package com.childenglish.controller;

import com.childenglish.entity.SysUser;
import com.childenglish.mapper.SysUserMapper;
import com.childenglish.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Autowired
    private SysUserMapper sysUserMapper;

    @PostMapping("/login")
    public R login(@RequestBody LoginRequest request) {
        try {
            System.out.println("登录请求: " + request.getUsername());

            // 从数据库查找用户（包含角色信息）
            SysUser user = sysUserMapper.findByUsername(request.getUsername());
            System.out.println("查询到的用户: " + (user != null ? user.getUsername() : "null"));
            System.out.println("用户角色: " + (user != null ? user.getRole() : "null"));

            if (user != null && user.getPassword().equals(request.getPassword())) {
                // 登录成功，返回用户信息和token
                Map<String, Object> data = new HashMap<>();
                data.put("user", user);
                data.put("token", "mock-token-" + System.currentTimeMillis());

                System.out.println("登录成功: " + user.getUsername() + " - 角色: " + user.getRole());
                return R.ok("登录成功").data(data);
            } else {
                System.out.println("登录失败: 用户名或密码错误");
                return R.error("用户名或密码错误");
            }
        } catch (Exception e) {
            System.out.println("登录异常: " + e.getMessage());
            e.printStackTrace();
            return R.error("登录失败: " + e.getMessage());
        }
    }

    @GetMapping("/user/info")
    public R getUserInfo() {
        // 这里应该从token中获取当前用户信息
        // 暂时返回空用户
        Map<String, Object> data = new HashMap<>();
        data.put("user", new SysUser());
        return R.ok().data(data);
    }

    // 登录请求对象
    public static class LoginRequest {
        private String username;
        private String password;

        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
}